package com.serli.sample.data.runner.view;

import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.ImageButton;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;

import com.serli.sample.data.runner.WicketApplication;
import com.serli.sample.data.runner.WicketSession;
import com.serli.sample.data.runner.domain.Trip;

public class TripList extends Panel {

	private static final long serialVersionUID = 1L;
	private WebMarkupContainer addContainer;

	public TripList(String id, IModel model) {
		super(id, model);
		prepareTripListCommands();
		prepareTripList(model);
	}

	private void prepareTripList(IModel model) {
		RepeatingView repeater = new RepeatingView("tripListItem");
		add(repeater);

		List<Trip> tripList = (List<Trip>) model.getObject();
		if (tripList != null && !tripList.isEmpty()) {
			for (Trip trip : tripList) {
				System.out.println(trip.getName());
				Link link = new Link("link_" + Long.toString(trip.getId()),
						new PropertyModel(trip, "name")) {
					public void onClick() {
						((WicketSession) getSession())
								.setSelectedName(getModelObjectAsString());
						setResponsePage(HomePage.class);
					}
				};
				link.add(new Label("tripListItemLabel", new PropertyModel(trip,
						"name")));
				repeater.add(link);
			}
		}
	}

	private void prepareTripListCommands() {
		addContainer = new WebMarkupContainer("tripEdit");
		addContainer.setOutputMarkupId(true);

		Form tripListCommands = new Form("tripListCommands") {
			@Override
			public void onSubmit() {
				System.out.println("Soumission du formulaire");
			}
		};
		tripListCommands.add(new AjaxButton("addCommand") {
			@Override
			protected void onSubmit(AjaxRequestTarget target, Form form) {
				System.out.println("Ajout d'un parcours");

				TripEdit tripEdit = new TripEdit("tripEdit");
				addContainer.replaceWith(tripEdit);
				addContainer = tripEdit;
				target.addComponent(tripEdit);
			}
		});
		tripListCommands.add(new ImageButton("removeCommand") {
			@Override
			public void onSubmit() {
				String tripName = ((WicketSession) getSession())
						.getSelectedName();
				if (tripName != null) {
					((WicketApplication) getApplication()).removeTrip(tripName);
					setResponsePage(HomePage.class);
				}
			}
		});

		add(tripListCommands);
		add(addContainer);
	}

}
